class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        srand(time(NULL));
        return qsort(nums, 0, nums.size() - 1, k);
    }
    int qsort(vector<int>& nums, int l, int r, int k) {
        if (l == r) return nums[l];
        int left = l - 1, right = r + 1, sign = l;
        int key = Getrandom(nums, l, r);
        while (sign < right) {
            if (nums[sign] < key)
                swap(nums[++left], nums[sign++]);
            else if (nums[sign] == key)
                sign++;
            else
                swap(nums[sign], nums[--right]);
        }
        if (r - right + 1 >= k)
            return qsort(nums, right, r, k);
        else if (r - left >= k)
            return key;
        else
            return qsort(nums, l, left, k - (r - left));
    }
    int Getrandom(vector<int>& nums, int left, int right) {
        int x = rand();
        return nums[x % (right - left + 1) + left];
    }
};
class Solution {
public:
    vector<int> inventoryManagement(vector<int>& nums, int cnt) {
        srand(time(NULL));
        qsort(nums, 0, nums.size() - 1, cnt);
        return { nums.begin(), nums.begin() + cnt };
    }
    void qsort(vector<int>& nums, int l, int r, int k) {
        if (l >= r) return;
        int left = l - 1, right = r + 1, sign = l;
        int key = Getrandom(nums, l, r);
        while (sign < right) {
            if (nums[sign] < key)
                swap(nums[++left], nums[sign++]);
            else if (nums[sign] == key)
                sign++;
            else
                swap(nums[sign], nums[--right]);
        }
        if (left - l + 1 > k) qsort(nums, l, left, k);
        else if (right - l >= k) return;
        else qsort(nums, right, r, k - (right - l));
    }
    int Getrandom(vector<int>& nums, int left, int right) {
        int x = rand();
        return nums[x % (right - left + 1) + left];
    }
};
